package club.smartdot.api.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

import club.smartdot.api.entity.UserEntity;
import club.smartdot.api.feign.MemberServiceFeign;
import club.smartdot.api.service.IOrderService;
import club.smartdot.base.BaseApiService;
import club.smartdot.base.ResponseBase;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(value = "订单服务接口")
@RestController
public class OrderServiceImpl extends BaseApiService implements IOrderService {
	
	@Autowired
	private MemberServiceFeign memberServiceFeign;

	@ApiOperation(value = "获取订单及用户信息")
	@RequestMapping(value = "/orderToMember")
	public String orderToMember(String name) {
		UserEntity user = memberServiceFeign.getMember(name);
		return user == null ? "没有找到用户信息" : user.toString();
	}

	
	// 此时没有解决服务雪崩效应
	@ApiOperation(value = "获取订单及用户信息(未解决雪崩效应)")
	@Override
	@RequestMapping(value = "/orderToMemberUserInfo")
	public ResponseBase orderToMemberUserInfo() {
		return memberServiceFeign.getUserInfo();
	}
	
	// 解决服务雪崩效应
	// @HystrixCommand默认开启线程池隔离，服务降级，服务熔断
	// 缺点，代码冗余,必须写本地服务降级方法，使用新的线程池进行服务隔离，以下方法所有代码都做了线程池隔离。
	@ApiOperation(value = "获取订单及用户信息(解决雪崩效应)")
	@HystrixCommand(fallbackMethod = "orderToMemberUserInfoHystrixFallback")
	@RequestMapping(value = "/orderToMemberUserInfoHystrix")
	public ResponseBase orderToMemberUserInfoHystrix() {
		System.out.println("线程池名称:" + Thread.currentThread().getName());
		return memberServiceFeign.getUserInfo();
	}
	
	// 服务降级执行
	public ResponseBase orderToMemberUserInfoHystrixFallback() {
		return setResultSuccess("返回一个友好的提示:服务器忙，请稍后重试!");
	}
	
	
	// 第二种方式:类的方式做服务降级,只对调用方法隔离
	@ApiOperation(value = "获取订单及用户信息(解决雪崩效应，类的方式隔离)")
	@RequestMapping(value = "/orderToMemberUserInfoHystrixDemo")
	public ResponseBase orderToMemberUserInfoHystrixDemo() {
		System.out.println("线程池名称:" + Thread.currentThread().getName());
		return memberServiceFeign.getUserInfo();
	}

	// 订单服务接口
	@ApiOperation(value = "订单服务接口")
	@Override
	@RequestMapping(value = "/orderInfo")
	public ResponseBase orderInfo() {
		System.out.println("线程池名称:" + Thread.currentThread().getName());
		return setResultSuccess();
	}

}
